package com.example.vietvoicecmdsimple;

import java.util.ArrayList;
import java.util.List;

import android.R.bool;
import android.R.string;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.media.MediaPlayer;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends Activity {
	public boolean IsDoAsking = false;
	public String ResultVoiceInput = "";
	private VObject cAction = null;
	
	private static final int RECOGNITION_REQUEST_CODE = 1992;
	
	private ExecuteCommand executeCommand;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		if (savedInstanceState == null) {
			getFragmentManager().beginTransaction()
					.add(R.id.container, new WellcomeScreenFragment()).commit();
		}
		VietTTSEngine.Init(this);
		VParameter.cr = getContentResolver();
		
		executeCommand = new ExecuteCommand();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		if (id == R.id.action_voice) {
			StartVoiceInput();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public Boolean checkVoiceRecognition() {
		// Check if voice recognition is present
		PackageManager pm = getPackageManager();
		List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
				RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		if (activities.size() == 0) {
			Toast.makeText(this, "Voice recognizer not present",
					Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	public void StartVoiceInput() {
		//VObject vObj = VoiceAnalyse.Analyse("Đánh thức sau 7 giờ 30 phút");
		//Toast.makeText(this, vObj.Action + "--" + vObj.Parameters[0].Value + "--" + vObj.Parameters[1].Question, Toast.LENGTH_LONG).show();
		// TODO Auto-generated method stub
		/*
		if (checkVoiceRecognition()) {
			// Intent detailsIntent =  new Intent(RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS);
			//		    sendOrderedBroadcast(
			//		            detailsIntent, null, new LanguageDetailsChecker(), null, Activity.RESULT_OK, null, null);
			Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

			// Specify the calling package to identify your application
			intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
					.getPackage().getName());

			// Display an hint to the user about what he should say.
			// intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
			// metTextHint.getText().toString());

			// Given an hint to the recognizer about what the user is going to
			// say
			// There are two form of language model available
			// 1.LANGUAGE_MODEL_WEB_SEARCH : For short phrases
			// 2.LANGUAGE_MODEL_FREE_FORM : If not sure about the words or
			// phrases and its domain.
			//intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
			//		RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
			
			///Set language
			intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "vi-VN");
			
			intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "vVoice listening...");
			// Specify how many results you want to receive. The results will be
			// sorted where the first result is the one with higher confidence.
			intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
			// Start the Voice recognizer activity for the result.
			startActivityForResult(intent, RECOGNITION_REQUEST_CODE);
		}
		*/
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == RECOGNITION_REQUEST_CODE)

			// If Voice recognition is successful then it returns RESULT_OK
			if (resultCode == RESULT_OK) {

				ArrayList<String> textMatchList = data
						.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

				if (!textMatchList.isEmpty()) {
					// If first Match contains the 'search' word
					// Then start web search.
					if (textMatchList.get(0).contains("search")) {

						String searchQuery = textMatchList.get(0);
						searchQuery = searchQuery.replace("tìm kiếm", "");
						Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
						search.putExtra(SearchManager.QUERY, searchQuery);
						startActivity(search);
					} else {
						// populate the Matches
						/*
						 * mlvTextMatches.setAdapter(new ArrayAdapter<string>(
						 * this, android.R.layout.simple_list_item_1,
						 * textMatchList));
						 */
						String input = textMatchList.get(0);
						showToastMessage(input);
						if (input.contains("hủy bỏ")){
							IsDoAsking = false;
						}
						if (!IsDoAsking){
							cAction = VoiceAnalyse.Analyse(input);
							IsDoAsking = true;
							getFragmentManager().beginTransaction()
							.add(R.id.container, new ResultFragment(cAction)).commit();
							for(int i = 0; i < VObject.MAXPARAMETERS; i++){
								if (cAction.Parameters[i].IsNeedAsk){
									VietTTSEngine.Speech(cAction.Parameters[i].Question);
									StartVoiceInput();
									break;
								}
							}
						}
						else
						{
							Boolean isCompleted = true;
							for(int i = 0; i < VObject.MAXPARAMETERS; i++){
								if (cAction.Parameters[i].IsNeedAsk){
									isCompleted = false;
									cAction.Parameters[i].Value = input;
									if (cAction.Parameters[i].Validate()){
										cAction.Parameters[i].IsNeedAsk = false;
										ResultFragment fragMent = (ResultFragment)getFragmentManager().findFragmentById(R.id.container);
										fragMent.SetText();
										if (i < VObject.MAXPARAMETERS - 1 && cAction.Parameters[i+1].IsNeedAsk){
											VietTTSEngine.Speech(cAction.Parameters[i+1].Question);
											StartVoiceInput();
											break;
										}
										else{
											isCompleted = true;
										}
									}
									else {
										isCompleted = false;
										VietTTSEngine.Speech("Nhập sai!" + cAction.Parameters[i].Question);
										StartVoiceInput();
										break;
									}
								}
							}
							if (isCompleted){
								IsDoAsking = false;
								//DoSomething here
							}
						}
						//PlaceholderFragment fragMent = (PlaceholderFragment)getFragmentManager().findFragmentById(R.id.container);
						//fragMent.setText(textMatchList.get(0));
					}

				}
				// Result code for various error.
			} else if (resultCode == RecognizerIntent.RESULT_AUDIO_ERROR) {
				showToastMessage("Audio Error");
			} else if (resultCode == RecognizerIntent.RESULT_CLIENT_ERROR) {
				showToastMessage("Client Error");
			} else if (resultCode == RecognizerIntent.RESULT_NETWORK_ERROR) {
				showToastMessage("Network Error");
			} else if (resultCode == RecognizerIntent.RESULT_NO_MATCH) {
				showToastMessage("No Match");
			} else if (resultCode == RecognizerIntent.RESULT_SERVER_ERROR) {
				showToastMessage("Server Error");
			}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * Helper method to show the toast message
	 **/
	void showToastMessage(String message) {
		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class WellcomeScreenFragment extends Fragment{
		
		public WellcomeScreenFragment() {
		}
		
		public void setText(String text){
			TextView tv = (TextView)getView().findViewById(R.id.textSayed);
			if (tv != null){
				tv.setText(text);
			}
		}
		
		@Override
		public void onCreate(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onCreate(savedInstanceState);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_start, container,
					false);
			ImageView imageView = (ImageView)rootView.findViewById(R.id.imgLogo);
			imageView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					((MainActivity)getActivity()).StartVoiceInput();
				}
			});
			return rootView;
		}
	}
	
	public static class ResultFragment extends Fragment
	{
		VObject vObj;
		public ResultFragment(VObject Obj){
			vObj = Obj;
		}
		
		public void SetText(){
			TextView title = (TextView)getView().findViewById(R.id.cmdTitle);
			if (title != null){
				title.setText(vObj.Action.toString());
			}
			
			TextView line1 = (TextView)getView().findViewById(R.id.lineOne);
			if (line1 != null && !vObj.Parameters[0].IsNeedAsk){
				line1.setText(vObj.Parameters[0].Value);
			}
			
			TextView line2 = (TextView)getView().findViewById(R.id.lineTwo);
			if (line2 != null && !vObj.Parameters[1].IsNeedAsk){
				line2.setText(vObj.Parameters[1].Value);
			}
			
			TextView line3 = (TextView)getView().findViewById(R.id.lineThree);
			if (line3 != null && !vObj.Parameters[2].IsNeedAsk){
				line3.setText(vObj.Parameters[2].Value);
			}
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);
			TextView title = (TextView)rootView.findViewById(R.id.cmdTitle);
			if (title != null){
				title.setText(vObj.Action.toString());
			}
			
			TextView line1 = (TextView)rootView.findViewById(R.id.lineOne);
			if (line1 != null && !vObj.Parameters[0].IsNeedAsk){
				line1.setText(vObj.Parameters[0].Value);
			}
			
			TextView line2 = (TextView)rootView.findViewById(R.id.lineTwo);
			if (line2 != null && !vObj.Parameters[1].IsNeedAsk){
				line2.setText(vObj.Parameters[1].Value);
			}
			
			TextView line3 = (TextView)rootView.findViewById(R.id.lineThree);
			if (line3 != null && !vObj.Parameters[2].IsNeedAsk){
				line3.setText(vObj.Parameters[2].Value);
			}
			return rootView;
		}
		
	}
}
